<?php

namespace Apps\AppApi\Method\Question;
use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Libs\PicUrl;
use Apps\Common\Models\QuestionAnswer;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Libs\Jpush;
use Apps\Common\Models\QuestionAnswerFollow;

/**
 * 问题列表，可通过分类筛选
 * @package Apps\AppApi\Method\Question
 */
class AnswerList extends BaseMethod
{
    public function run()
    {
        $questionId = intval($this->getDataItem('question_id', 0));
        $user_id = intval($this->getDataItem('user_id', 0));
        $page = intval($this->getDataItem('page', 1));

//        $questionId = 194;

        if ($questionId < 1) {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, '参数不完整或者参数错误！');
        }

        $limit = $this->getConfig()->limit;
        $offset = ($page-1) * $limit;

        $QuestionAnswer = new QuestionAnswer();

        $expertReplyList = $QuestionAnswer->query()->columns([
            'u.user_id',
            'u.user_cover',
            'u.user_nickname',
            'u.user_gender',
            'answer_id',
            'answer_content',
            'original_content',
            'support_count',
            'answer_addtime',
            'answer_pics',
        ])->leftJoin('\Apps\Common\Models\UserBase', 'u.user_id = \Apps\Common\Models\QuestionAnswer.user_id', 'u')->where("answer_state = 1 and type = 1 and question_id = {$questionId}")->orderBy('answer_addtime DESC')->limit($limit, $offset)->execute()->toArray();

        $QuestionAnswerFollow = new QuestionAnswerFollow();
        foreach ($expertReplyList as $k => $val) {
            $expertReplyList[$k]['user_cover'] = PicUrl::UserCover($val['user_cover'], $this->getDi());
            $expertReplyList[$k]['answer_content'] = unserialize(base64_decode($val['answer_content'])) ?: $val['answer_content'];

            if ($user_id > 0) {
                $expertReplyList[$k]['is_support'] = $QuestionAnswerFollow->is_support($user_id, $val['answer_id']) ? '1' : '0';
            } else {
                $expertReplyList[$k]['is_support'] = '0';
            }

            $answer_pics = [];
            if ($answer_pics_list = json_decode($val['answer_pics'], true)) {
                foreach ($answer_pics_list as $value) {
                    $answer_pics[] = PicUrl::Question($value, $this->getDi());
                }
            }
            $expertReplyList[$k]['answer_pics'] = $answer_pics;
            $expertReplyList[$k]['original_content'] = unserialize(base64_decode($val['original_content'])) ?: $val['original_content'];
        }

        $this->setResult($expertReplyList);
    }

}